package com.gztms.usermgnt.pojo;

import com.alibaba.fastjson.annotation.JSONField;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Zoey
 * @date 2023/3/8 0:24
 * @Description 登录用户信息类
 **/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class LoginUser implements UserDetails {

    private User user;
    private List<String> permissions;
    private SysRole role;
    @JSONField(serialize = false)
    private List<SimpleGrantedAuthority> authorities;
    public LoginUser(User user, SysRole role){
        this.user = user;
        this.role = role;
    }

    public LoginUser(User user, List<String> permissions) {
        this.user = user;
        this.permissions = permissions;
    }

    // 权限信息
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if (authorities!=null) {
            return authorities;
        }

        // 将permissions中string类型的权限信息封装成SimpleGrantedAuthority对象
       authorities = permissions.stream()
                .map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());
        return authorities;

    }


    @Override
    public String getPassword() {
        return user.getPassword();
    }

    /**
     * 注意这里返回的是uid
     * @return
     */
    @Override
    public String getUsername() {
        return user.getUid();
    }

    /**
     * 判断用户是否过期
     * @return
     */
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    /**
     * 被锁
     * @return
     */
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    /**
     * 判断账号是否可用
     * @return
     */
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
